
"""
    tcp服务端3.0
    根据请求的路径不同返回不同的页面
"""

import socket


def request_handler(tcp_client, ip_port):
    request_data = tcp_client.recv(1024)

    # print(recv_data)

    # 判断客户端是否断开连接，但是目前有问题，还不知道怎么解
    if not request_data:
        print("%s客户端断开连接" % str(ip_port))
        tcp_client.close()
        return

    # print(recv_data)
    request_text = request_data.decode()
    loc = request_text.find("\r\n")
    request_line = request_text[:loc]
    request_line_list = request_line.split(" ")
    file_name = request_line_list[1]
    # print(file_path)
    file_path = "D:\\python-workstation\\study_dir\\002_http_study"

    response_line = "HTTP/1.1 200 OK\r\n"
    response_header = "Server:Python20WS/0.1\r\n"
    response_blank = "\r\n"
    with open(file_path + file_name, "r") as file:
        file_data = file.read()

    response_body = file_data

    response_data = response_line + response_header + response_blank + response_body

    tcp_client.send(response_data.encode())
    tcp_client.close()


def init():
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

    tcp_server.bind(("192.168.0.107", 8080))
    tcp_server.listen(128)

    while True:
        new_tcp_client,ip_port = tcp_server.accept()
        print("%s客户端已连接" % str(ip_port))

        request_handler(new_tcp_client, ip_port)

    # tcp_server.close()


if __name__ == '__main__':
    init()
